package com.xpgk.mvc.binShopService;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.bouncycastle.asn1.eac.Flags;

import org.apache.commons.lang.StringUtils;


import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.FieldAccessor_Float;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerHabit;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.bloseWeight.DelWeiTarget;
import com.xpgk.mvc.bloseWeight.DelWeiTargetSum;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.productSet.ProductExperience;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolDateTime;

import jodd.typeconverter.impl.BooleanArrayConverter;
import oracle.net.aso.n;
import sun.java2d.pipe.SpanShapeRenderer.Simple;

@Service(name = BinShopServiceService.serviceName)
public class BinShopServiceService extends BaseService {
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BinShopServiceService.class);
	public static final String serviceName = "binShopServiceService";
	
	/**塑形，获取服务部信息
	 * 
	 * @param customerIds
	 * @param curUserIds
	 * @return
	 */
	public List<Map> getPartInfo(String customerIds, String curUserIds) {
		List<Map> partInfoList = new ArrayList<>();
		// 获取服务部位
		List<Code> codeList = Code.cacheGetChild(Code.fwbw_ids);
		if (codeList != null && codeList.size() > 0) {
			for (int i = 0; i < codeList.size(); i++) {
				Map<String, String> map = new HashMap<>();
				map.put("positionIds", codeList.get(i).getStr(Code.column_ids));
				map.put("position", codeList.get(i).getStr(Code.column_name));
				map.put("userids", curUserIds);
				map.put("name", User.cacheGetByUserId(curUserIds).getStr(User.column_name));
				String cusprosql = getSqlMy(CustomerProduct.sqlId_selByCusAndUseIdsAndPartIds);
				List<CustomerProduct> cpList = CustomerProduct.dao.find(cusprosql, Code.cpytFw_ids, customerIds,
						codeList.get(i).getStr(Code.column_ids));
				if (cpList != null && cpList.size() > 0) {
					for (int j = 0; j < cpList.size(); j++) {
						map.put(cpList.get(j).getStr(Product.column_ids), cpList.get(j).getStr(Product.column_ids));
						map.put("use_" + cpList.get(j).getStr(Product.column_ids),
								cpList.get(j).getFloat(ProductExperience.column_experience).toString());
						map.put("surplus_" + cpList.get(j).getStr(Product.column_ids),
								cpList.get(j).getFloat(CustomerProduct.column_totalExperience).toString());
					}
				}
				partInfoList.add(map);
			}

		}

		return partInfoList;

	}

	/**
	 * 获取测量部位尺寸
	 * 
	 * @param customerIds
	 * @return
	 */
	public List<Map> getPartSizeInfo(String customerIds) {
		List<Map> partSizeInfoList = new ArrayList<>();
		// 获取服务部位
		List<Code> codeList = Code.cacheGetChild(Code.fwbw_ids);
		for(Code code:codeList)
		{
			List<Code> cList = Code.cacheGetChild(code.getStr(Code.column_ids));
			for(Code cc:cList){
				Map<String, String> map = new HashMap<>();
				map.put("positionIds", cc.getStr(Code.column_ids));
				map.put("position", cc.getStr(Code.column_name));
				List<ServicePartSize>  spsList=ServicePartSize.dao.getServicePartSize(customerIds,cc.getStr(Code.column_ids));
				if(spsList!=null &&  spsList.size()>0)
				{
					map.put("positionSize", spsList.get(0).getFloat(ServicePartSize.column_size).toString());
				}else
				{
					map.put("positionSize", "0");
				}
				partSizeInfoList.add(map);
			}
		}

		return partSizeInfoList;
	}

	/**
	 * 获取默认生活习惯
	 * 
	 * @param cusIds
	 * @param orgIds
	 * @return
	 */
	public CustomerHabit getCusHabit(String cusIds, String orgIds) {
		String servicesql = getSqlMy(CustomerService.sqlId_selByCusAndOrg);
		List<CustomerService> csList = CustomerService.dao.find(servicesql, cusIds, orgIds);
		if (csList != null && csList.size() > 0) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", CustomerHabit.column_serviceID);
			String sql = getSqlByBeetl(CustomerHabit.sqlId_column, param);
			CustomerHabit ch = CustomerHabit.dao.findFirst(sql, csList.get(0).getStr(CustomerService.column_ids));
			if (ch != null) {
				return ch;
			} else {
				return null;
			}

		} else {
			return null;
		}
	}

//	/**
//	 * 保存服务和生活习惯
//	 * 
//	 */
//	public String saveInfo(Customer c, CustomerHabit ch, CustomerService cs, String orgIds, String userIds,
//			List<ServicePartSize> spsList, List<ServiceShaping> ssList, List<CustomerProduct> cpList,
//			String plaster_ids) {
//		String msg = ConstantRender.render_success_code; 
//		
//		CustomerDetail cd = c.getCustomerDetail();
//		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
//		String gxsj = "%" + dateFormater.format(new Date()) + "%";
//		// 保存服务记录
//		cs.set(CustomerService.column_organids, orgIds)
//				.set(CustomerService.column_customerID, c.getStr(Customer.column_ids))
//				.set(CustomerService.column_userID, userIds)
//				.set(CustomerService.column_lastWeight, cd.getFloat(CustomerDetail.column_nowWeight))
//				.set(CustomerService.column_createDate, new Date());
//		if (!cs.save()) {
//			log.debug("保存服务记录失败");
//			throw new RuntimeException("保存服务记录失败!");
//		}
//		if (cs.getStr(CustomerService.column_isPlaster).equals("1")) {
//			String plaster[] = plaster_ids.split(",");
//			for (int i = 0; i < plaster.length; i++) {
//				if (plaster[i] != null && !plaster[i].equals("")) {
//					Product p = Product.dao.findById(plaster[i]);
//					String pstSql = getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
//					ProductStock pst = ProductStock.dao.findFirst(pstSql, orgIds, p.getStr(Product.column_ids));
//					if (pst != null && pst.getFloat(ProductStock.column_num) >= 1) 
//					{
//						//保存药贴出库记录
//						ProductOutin  po = new  ProductOutin();
//						po.set(ProductOutin.column_ids, ToolRandoms.getUuid(true))
//							.set(ProductOutin.column_organIds, orgIds)
//							.set(ProductOutin.column_typeIds, p.getStr(Product.column_typeIds))
//							.set(ProductOutin.column_productIds, p.getStr(Product.column_ids))
//							.set(ProductOutin.column_number, 1)
//							.set(ProductOutin.column_price, 0)
//							.set(ProductOutin.column_date, new Date())
//							.set(ProductOutin.column_style, "1")
//							.set(ProductOutin.column_userIds, userIds)
//							.set(ProductOutin.column_gxsj, new Date());
//						if(!po.save())
//						{
//							log.debug("保存"+p.getStr(Product.column_name) +"出库记录失败！！");
//							throw new RuntimeException("保存"+p.getStr(Product.column_name) + "出库记录失败！！");
//						}
//						// 更新产品库存
//						
//						// 根据日期和机构id,产品id查出当日是否有库存记录
//						String pstInsql = getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
//						ProductStockInfo psi = ProductStockInfo.dao.findFirst(pstInsql, orgIds,
//								p.getStr(Product.column_ids), gxsj);
//					
//							float num1 = pst.getFloat(ProductStock.column_num) - 1;
//							pst.set(ProductStock.column_num, num1).set(ProductStock.column_gxsj, new Date());
//							if (!pst.update()) {
//								log.debug("更新产品总库存失败");
//								throw new RuntimeException("更新产品总库存失败!");
//							}
//							if (psi != null) {
//								// 库存详细信息减少库存
//								float num = psi.getFloat(ProductStockInfo.column_stock) - 1;
//								psi.set(ProductStockInfo.column_stock, num)
//										.set(ProductStockInfo.column_gxsj, new Date()).update();
//
//							} else {
//								ProductStockInfo psInfo = new ProductStockInfo();
//								String psinfoids = ToolRandoms.getUuid(true);
//								psInfo.set(ProductStockInfo.column_ids, psinfoids)
//										.set(ProductStockInfo.column_organids, orgIds)
//										.set(ProductStockInfo.column_productID, p.getStr(Product.column_ids))
//										.set(ProductStockInfo.column_type, p.getStr(Product.column_typeIds))
//										.set(ProductStockInfo.column_stock, pst.getFloat(ProductStock.column_num))
//										.set(ProductStockInfo.column_gxsj, new Date());
//								if (!psInfo.save()) {
//									log.debug("保存产品库存记录失败！！");
//									throw new RuntimeException("保存产品库存记录失败!");
//								}
//							}
//						} else {
//							log.debug(p.getStr(Product.column_name) + "库存不够，无法购买！！");
////							throw new RuntimeException(p.getStr(Product.column_name) + "库存不够，请先入库！！");
//							msg=p.getStr(Product.column_name) + "库存不够，请先入库！！";
//						}
//				}
//			}
//		}
//		//如果顾客为单疗程顾客，到店服务一次减少一次单疗程次数
//		String  lcsql=getSqlMy(CustomerProduct.sqlId_selByCusAndType);
//		CustomerProduct  lccp = CustomerProduct.dao.findFirst(lcsql,c.getStr(Customer.column_ids),Code.lc_ids,orgIds);
//		if(lccp!=null && lccp.getStr("proUnits").equals(Code.dlc_units))
//		{
//			CustomerProduct  dlccp=CustomerProduct.dao.findById(lccp.getStr("ids"));
//			dlccp.set(CustomerProduct.column_totalExperience, dlccp.getFloat(CustomerProduct.column_totalExperience)-1)
//				.set(CustomerProduct.column_updateDate, new Date());
//			if (!dlccp.update()) {
//				log.debug("更新单疗程剩余失败");
//				throw new RuntimeException("更新单疗程剩余失败!");
//			}
//		}
//				
//				
//				
//				
//		
//		// 保存塑形
//		if (ssList.size() > 0) {
//			for (ServiceShaping ss : ssList) {
//				ss.set(ServiceShaping.column_serviceIds, cs.getStr(CustomerService.column_ids))
//						.set(ServiceShaping.column_customerIds, c.getStr(Customer.column_ids))
//						.set(ServiceShaping.column_time, new Date());
//				if (!ss.save()) {
//					log.debug("保存塑形失败");
//					throw new RuntimeException("保存塑形失败!");
//				}
//			}
//			// 更新产品剩余量
//			if (cpList.size() > 0) {
//				for (CustomerProduct cp : cpList) {
//
//					String cpSql = getSqlMy(CustomerProduct.sqlId_selByCusAndPro);
//					CustomerProduct cuspro = CustomerProduct.dao.findFirst(cpSql, c.getStr(Customer.column_ids),
//							cp.getStr(CustomerProduct.column_productID), orgIds);
//					CustomerProductSurplus  cps=CustomerProductSurplus.dao.getCustomerProductSurplus(c.getStr(Customer.column_ids), cp.getStr(CustomerProduct.column_productID), orgIds, gxsj);
//					if (cuspro != null) {
//						double num=Math.ceil(cp.getFloat(CustomerProduct.column_totalExperience)/cuspro.getFloat(CustomerProduct.column_proExperience));
//						cuspro.set(CustomerProduct.column_capacities, cp.getFloat(CustomerProduct.column_capacities))
//								.set(CustomerProduct.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
//						        .set(CustomerProduct.column_count, num)
//								.set(CustomerProduct.column_updateDate, new Date());
//						if (!cuspro.update()) {
//							log.debug("更新产品剩余量失败");
//							throw new RuntimeException("更新产品剩余量失败!");
//						}
//						if(cps!=null)
//						{
//							//更新顾客产品剩余详细信息
//							cps.set(CustomerProductSurplus.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
//							.set(CustomerProductSurplus.column_count, num)
//							.set(CustomerProductSurplus.column_gxsj, new Date());
//							if (!cps.update()) {
//								log.debug("更新顾客产品明细失败！！");
//								throw new RuntimeException("更新顾客产品明细失败!");
//							}
//						}else
//						{
//							//保存顾客产品剩余详细信息
//							Product  p=Product.dao.findById(cp.getStr(CustomerProduct.column_productID));
//							CustomerProductSurplus  cusprosur=new CustomerProductSurplus();
//							cusprosur.set(CustomerProductSurplus.column_ids, ToolRandoms.getUuid(true))
//									.set(CustomerProductSurplus.column_organIds, orgIds)
//									.set(CustomerProductSurplus.column_customerIds, c.getStr(Customer.column_ids))
//									.set(CustomerProductSurplus.column_productIds, cp.getStr(CustomerProduct.column_productID))
//									.set(CustomerProductSurplus.column_count, num)
//									.set(CustomerProductSurplus.column_proExperience,  p.getStr(Product.column_proExperience))
//									.set(CustomerProductSurplus.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
//									.set(CustomerProductSurplus.column_gxsj, new Date());
//							if (!cusprosur.save()) {
//								log.debug("保存顾客产品明细失败！！");
//								throw new RuntimeException("保存顾客产品明细失败!");
//							}
//						}
//					}
//				}
//			}
//		}
//
//		
//		// 保存尺寸
//		if (spsList.size() > 0) {
//			for (ServicePartSize sps : spsList) {
//				sps.set(ServicePartSize.column_serviceIds, cs.getStr(CustomerService.column_ids))
//						.set(ServicePartSize.column_customerIds, c.getStr(Customer.column_ids))
//						.set(ServicePartSize.column_createDate, new Date());
//				if (!sps.save()) {
//					log.debug("保存测量尺寸失败");
//					throw new RuntimeException("保存测量尺寸失败!");
//				}
//			}
//		}
//		// 更新顾客详情本次体重和到店时间
//
//		if (cd != null) {
//			cd.set(CustomerDetail.column_nowWeight, cs.getFloat(CustomerService.column_weight))
//					.set(CustomerDetail.column_toStoreDate, new Date());
//			if (!cd.update()) {
//				log.debug("更新顾客详情本次体重和到店时间失败");
//				throw new RuntimeException("更新顾客详情本次体重和到店时间失败!");
//			}
//		}
//		//保存顾客日常
//		ch.set(CustomerHabit.column_serviceID, cs.getStr(CustomerService.column_ids))
//			.set(CustomerHabit.column_customerID, c.getStr(Customer.column_ids))
//			.set(CustomerHabit.column_organIds, orgIds)
//		    .set(CustomerHabit.column_gxsj, new Date());
//		if(!ch.save())
//		{
//			log.debug("保存顾客生活日常失败");
//			throw new RuntimeException("保存顾客生活日常失败!");
//		}
//		
//		return msg;
//
//	}
	
	public  void  saveTotalInfo(String customerIds,String cudid ,boolean flag)
	{	
		DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cudid,new Date());
		
		if(dnt != null)
		{
			dnt.set(DailyNursingTotal.column_sddrs, dnt.getInt(DailyNursingTotal.column_sddrs)+1)
				.set(DailyNursingTotal.column_fwcs, dnt.getInt(DailyNursingTotal.column_fwcs)+1);
			if(flag){
				dnt.set(DailyNursingTotal.column_xgkddrs, dnt.getInt(DailyNursingTotal.column_xgkddrs)+1);
			}
			
			if (!dnt.update()) {
				log.debug("更新日综合查询表失败");
				throw new RuntimeException("更新日综合查询表失败!");
			}
		}else
		{
			dnt = new DailyNursingTotal();
			String sql = "SELECT * FROM sb_customer_total_daily WHERE organids = ? ORDER BY date DESC";
			DailyNursingTotal olddnt = DailyNursingTotal.dao.findFirst(sql,cudid);
			dnt.set(DailyNursingTotal.column_organids, cudid)
				  .set(DailyNursingTotal.column_date, ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd))
				  .set(DailyNursingTotal.column_sddrs, 1)
				 
				  .set(DailyNursingTotal.column_fwcs, 1);
			if(flag){
				dnt.set(DailyNursingTotal.column_xgkddrs, 1);
			}
			
			if (!dnt.save()) {
				log.debug("保存日综合查询表失败");
				throw new RuntimeException("保存日综合查询表失败!");
			}
		}
	}
	
	public  void saveServiceInfo(CustomerDetail cdet,CustomerService cs,String customerIds,String cudid,String userid,boolean isXgk)
	{		
		DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cudid,new Date());
		
				
				
				if(dnt != null)
				{

					if(null != cdet.getStr(CustomerDetail.column_customerType) && cdet.getStr(CustomerDetail.column_customerType).equals("0"))
					{	
						float  cjs = cs.getFloat(CustomerService.column_weight) - cs.getFloat(CustomerService.column_lastWeight);
						float dcjs = Float.parseFloat(new DecimalFormat("#.0").format(cjs));
						
						if( dcjs < 0.00)
						{
							dnt.set(DailyNursingTotal.column_dcrs, dnt.getInt(DailyNursingTotal.column_dcrs)+1)
								.set(DailyNursingTotal.column_dcjs, dnt.getDouble(DailyNursingTotal.column_dcjs)+(-dcjs));
							if(isXgk){
								dnt.set(DailyNursingTotal.column_xgkdcrs, dnt.getInt(DailyNursingTotal.column_xgkdcrs)+1)
								.set(DailyNursingTotal.column_xgkdcjs, dnt.getDouble(DailyNursingTotal.column_xgkdcjs)+(-dcjs));
							}
						}
						if(dcjs == 0.00)
						{
							dnt.set(DailyNursingTotal.column_pcrs, dnt.getInt(DailyNursingTotal.column_pcrs)+1);
						}
						if( dcjs > 0.00)
						{
							dnt.set(DailyNursingTotal.column_zcrs, dnt.getInt(DailyNursingTotal.column_zcrs)+1)
								.set(DailyNursingTotal.column_zcjs, dnt.getDouble(DailyNursingTotal.column_zcjs)+dcjs);
							if(isXgk){
								dnt.set(DailyNursingTotal.column_xgkzcrs, dnt.getInt(DailyNursingTotal.column_xgkzcrs)+1)
								.set(DailyNursingTotal.column_xgkzcjs, dnt.getDouble(DailyNursingTotal.column_xgkzcjs)+dcjs);
							}
						}
					}else if(null != cdet.getStr(CustomerDetail.column_customerType) && cdet.getStr(CustomerDetail.column_customerType).equals("2"))
					{
						dnt.set(DailyNursingTotal.column_ggrs, dnt.getInt(DailyNursingTotal.column_ggrs)+1);
					}
//					double  dcbl = ((double)dnt.getInt(DailyNursingTotal.column_dcrs))/((double)(dnt.getInt(DailyNursingTotal.column_sddrs)-dnt.getInt(DailyNursingTotal.column_ggrs)+dnt.getInt(DailyNursingTotal.column_dbrs)));
//					dnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
					if (!dnt.update()) {
						/*log.debug("更新日综合查询表失败");
						throw new RuntimeException("更新日综合查询表失败!");*/
					}
				}
				else
				{	
					
					DailyNursingTotal  dntNew = new DailyNursingTotal();
					dntNew.set(DailyNursingTotal.column_organids, cudid)
						  .set(DailyNursingTotal.column_date, ToolDateTime.format(new Date(), ToolDateTime.pattern_ymd));
//						
					if(null != cdet.getStr(CustomerDetail.column_customerType) && cdet.getStr(CustomerDetail.column_customerType).equals("0"))
					{	
						float  cjs = cs.getFloat(CustomerService.column_weight) - cs.getFloat(CustomerService.column_lastWeight);
						float dcjs = Float.parseFloat(new DecimalFormat("#.0").format(cjs));
						if( dcjs < 0.00)
						{
							dntNew.set(DailyNursingTotal.column_dcrs, 1)
								.set(DailyNursingTotal.column_dcjs, (-dcjs));
							if(isXgk){
								dntNew.set(DailyNursingTotal.column_xgkdcrs,1)
								.set(DailyNursingTotal.column_xgkdcjs,(-dcjs));
							}
//							double  dcbl = ((double)dntNew.getInt(DailyNursingTotal.column_dcrs))/((double)dntNew.getInt(DailyNursingTotal.column_sddrs));
//							dntNew.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
						}
						if(dcjs == 0.00)
						{
							dntNew.set(DailyNursingTotal.column_pcrs,1);
						}
						if( dcjs > 0.00)
						{
							dntNew.set(DailyNursingTotal.column_zcrs, 1)
								.set(DailyNursingTotal.column_zcjs,dcjs);
							
							if(isXgk){
								dntNew.set(DailyNursingTotal.column_xgkzcrs,1)
								.set(DailyNursingTotal.column_xgkzcjs,(dcjs));
							}
						}
					}else if(null != cdet.getStr(CustomerDetail.column_customerType) && cdet.getStr(CustomerDetail.column_customerType).equals("2"))
					{
						dntNew.set(DailyNursingTotal.column_ggrs, 1);
					}
					if (!dntNew.save()) {
						log.debug("保存日综合查询表失败");
						throw new RuntimeException("保存日综合查询表失败!");
					}
				}
			
			
	}
	
	
	

	/**
	 * 获取减重计划
	 * 
	 * @param cusIds
	 * @return
	 */
	public Map<String,Object> getDelweight(String cusIds, String date, String orgids) {
		String msg = ConstantRender.render_success_code;
		Map<String, Object>  map=new  HashMap<>();
		List list = new ArrayList<>();
		String sql = getSqlMy(DelWeiTargetSum.sqlId_selByCusAndDate);
		List<DelWeiTargetSum> dtsList = DelWeiTargetSum.dao.find(sql, cusIds, date, date);
		if (dtsList != null && dtsList.size() > 0 && dtsList.size() < 2) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", DelWeiTarget.column_targetIds);
			String dwtsql = getSqlByBeetl(DelWeiTarget.sqlId_column, param);
			List<DelWeiTarget> dwtList = DelWeiTarget.dao.find(dwtsql, dtsList.get(0).getStr(DelWeiTarget.column_ids));
			if (dwtList != null && dwtList.size() > 0) {
				for (DelWeiTarget dwt : dwtList) {
					Map mm = new HashMap<>();
					mm.put("schedules", dwt.getStr(DelWeiTarget.column_schedule));
					mm.put("starttime", dwt.getDate(DelWeiTarget.column_startTime));
					mm.put("endtime", dwt.getDate(DelWeiTarget.column_endTime));
					mm.put("planner", dwt.getInt(DelWeiTarget.column_planToStoreNum));
					String serSql = getSqlMy(CustomerService.sqlId_selByDate);
					List<CustomerService> csList = CustomerService.dao.find(serSql, cusIds, orgids,
							dwt.getDate(DelWeiTarget.column_startTime).toString(),
							dwt.getDate(DelWeiTarget.column_endTime).toString());
					mm.put("reality", csList.size());
					// 创建一个数值格式化对象
					NumberFormat numberFormat = NumberFormat.getInstance();
					// 设置精确到小数点后2位
					numberFormat.setMaximumFractionDigits(2);
					float wcbl = 0;
					float delweight = 0;
					if (csList != null && csList.size() > 0) {
						wcbl = (float) csList.size() / (float) dwt.getInt(DelWeiTarget.column_planToStoreNum);
						delweight = csList.get(0).getFloat(CustomerService.column_weight)
								- csList.get(csList.size() - 1).getFloat(CustomerService.column_weight);
					}
					String jzjs = numberFormat.format(delweight / dwt.getFloat(DelWeiTarget.column_delWeiTarget) * 100);
					mm.put("analogy", numberFormat.format(wcbl * 100) + "%");
					mm.put("effect", jzjs + "%");
					list.add(mm);
				}
			}
		}
		if (dtsList.size() > 1) {
			msg = "一个顾客在同时期只能有一个总排期，请检查该顾客减重目标管理排期设置！";
		}
		map.put("msg", msg);
		map.put("delWeightList", list);
		return map;
	}

	/**
	 * 获取减重计划
	 * 
	 * @param cusIds
	 * @return
	 * @throws ParseException
	 */
	public List<CustomerService> getDelweiRecord(String orgids, String cusIds, String date) throws ParseException {
		String d="%"+date+"%";
		String sql = getSqlMy(CustomerService.sqlId_selByMonth);
		List<CustomerService> cs = CustomerService.dao.find(sql, cusIds, orgids, d);
		return cs;
	}

	public List<Record> getView(String cUserOrganIds,String name ,String phone ,String hybh) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organids", cUserOrganIds);
		 queryParam.put("name", name);
		 queryParam.put("phone", phone);
		 queryParam.put("hybh", hybh);
		
		 List<Record> lis = find(CustomerService.sqlId_selSerByOrganids, queryParam);
		return lis;
	}

	public List<Record> getTodayView(String cUserOrganIds, String name, String phone, String hybh,String date) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organids", cUserOrganIds);
		 queryParam.put("name", name);
		 queryParam.put("phone", phone);
		 queryParam.put("hybh", hybh);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 queryParam.put("today", date);
//		 queryParam.put("today", "2017-10-10");
		 
		 //45564564
		 List<Record> lis = find(CustomerService.sqlId_selSerTodayByOrganids, queryParam);
		return lis;
	}
	
	public List<Record> dlgetTodayView(String cUserOrganIds,String date) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organids", cUserOrganIds);
		 
		 queryParam.put("today", date);
		 
		 List<Record> lis = find(CustomerService.sqlId_selSerTodayByOrganids, queryParam);
		return lis;
	}
	

	
	/**今日服务合计功能数据
	 * 
	 * @param cUserOrganIds 机构Ids
	 * @return
	 */
	public Record totaloftodayservice(String cUserOrganIds,String date){
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Record record = new Record();
		String sql = "SELECT * FROM sb_customer_service WHERE organids = ? and DATE_FORMAT(startTime,'%Y-%m-%d')= ? and dataStatus in ('1','2')";
		String lastSql = "SELECT * from sb_customer_service  where  customerID = ?  AND   DATE_FORMAT(startTime, '%Y-%m-%d') <  ?     and dataStatus in ('1','2')   ORDER BY  startTime    DESC   LIMIT 0,1";//上次服务
		List<CustomerService> csList = CustomerService.dao.find(sql,cUserOrganIds,date);
		int ddrs =0;
		int ggrs = 0;
		float zcjs = 0f;
		float dcjs = 0f;
		int pcrs = 0;
		int zcrs = 0;
		int dcrs = 0;
		int xzrs = 0;
		int jhrs = 0;
		float js = 0f;
		if(csList!=null && csList.size()>0){
			//到店人数
			ddrs = csList.size();
			for(CustomerService cs:csList){
				String cusIds = cs.getStr(CustomerService.column_customerID);//今日服务的顾客id
				String sqlcdet = "select DATE_FORMAT(firstDate, '%Y-%m-%d') firstDate from sb_customer_detail WHERE customerIds = ? and dataStatus in ('1','2')";
				Record cdet  = Db.findFirst(sqlcdet,cusIds);
				if(cdet!=null && cdet.getStr("firstDate")!=null){
					
					if(cdet.getStr("firstDate").equals(date)){
						xzrs ++;
					}
					
				}
				String isGg = cs.getStr(CustomerService.column_isGg);
				String isShaping = cs.getStr(CustomerService.column_isShaping);
				if(isShaping!=null && isShaping.equals("1")){
					jhrs++;
				}
				if(isGg!=null){
					if(isGg.equals("1")){//如果今日服务是巩固 判断上次是否是巩固
						CustomerService last = CustomerService.dao.findFirst(lastSql,cusIds,date);
						if(last!=null && last.getStr(CustomerService.column_isGg).equals("1")){
							ggrs ++;
						}else{
							js = cs.getFloat(CustomerService.column_weight)-cs.getFloat(CustomerService.column_lastWeight);
							if(js == 0){
								pcrs++;
							}else if(js>0){
								zcrs++;
								zcjs = zcjs+js;
							}else if(js<0){
								dcrs++;
								dcjs = dcjs+ (-js);
							}
						}
					}else if(isGg.equals("0")){
						js = cs.getFloat(CustomerService.column_weight)-cs.getFloat(CustomerService.column_lastWeight);
						if(js == 0){
							pcrs++;
						}else if(js>0){
							zcrs++;
							zcjs = zcjs+js;
						}else if(js<0){
							dcrs++;
							dcjs = dcjs+ (-js);
						}
					}
				}
			}
			 
		}
		
		/*String sqloftotalofpeople = "SELECT count(*) AS totalofpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? and sbcs.dataStatus in ('1','2')";
		//到店人数不算巩固
		String sqloftotalofpeoplenogg = "SELECT count(*) AS totalofpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? and sbcs.dataStatus in ('1','2') and sbcs.isGg = '0'";
		//涨秤人数
		String sqloftotalofupweightpeople = "SELECT count(*) AS totalofupweightpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight>0 and isGg = '0' and sbcs.dataStatus in ('1','2')";
		//平秤人数
		String sqloftotalofnoloseweight = "SELECT count(*) AS totalofnoloseweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight=0 and isGg = '0' and sbcs.dataStatus in ('1','2')";
		//减秤人数
		String sqloftotalofdownweightpeople = "SELECT count(*) AS totalofdownweightpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight<0 and isGg = '0' and sbcs.dataStatus in ('1','2')";
		//涨秤斤数
		String sqlupweight = "SELECT SUM( sbcs.weight - sbcs.lastWeight ) AS upweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.weight - sbcs.lastWeight > 0 and isGg = '0' and sbcs.dataStatus in ('1','2')";
		//掉秤斤数
		String sqldownweight = "SELECT SUM( sbcs.lastWeight - sbcs.weight ) AS downweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.weight - sbcs.lastWeight < 0 and isGg = '0' and sbcs.dataStatus in ('1','2')";
		//精护人数
		String sqljinghu = "SELECT count(sbcs.isShaping) AS jinghu FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.isShaping = '1' and sbcs.dataStatus in ('1','2')";
		//巩固人数
		String sqlofgonggu = "SELECT count(*) AS gonggurenshu FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') =? AND sbcs.isGg = '1' and sbcs.dataStatus in ('1','2')";
		Record result = Db.findFirst(sqloftotalofpeople,cUserOrganIds,date);
		Record resultnogg = Db.findFirst(sqloftotalofpeoplenogg,cUserOrganIds,date);
		Record resultupweight = Db.findFirst(sqloftotalofupweightpeople,cUserOrganIds,date);
		Record resultdownweight = Db.findFirst(sqloftotalofdownweightpeople,cUserOrganIds,date);
		Record resultnoloseweight = Db.findFirst(sqloftotalofnoloseweight,cUserOrganIds,date);
		Record upweight = Db.findFirst(sqlupweight,cUserOrganIds,date);
		Record downweight = Db.findFirst(sqldownweight,cUserOrganIds,date);
		Record jinghu = Db.findFirst(sqljinghu,cUserOrganIds,date);
		Record gonggu = Db.findFirst(sqlofgonggu,cUserOrganIds,date);*/
		record.set("date",date)
			  .set("totalofpeople",ddrs)
			  .set("xzrs",xzrs)
			  .set("totalofupweightpeople",zcrs)
			  .set("totalofdownweightpeople", dcrs)
			  .set("totalofnoloseweight", pcrs)
			  .set("upweight", new DecimalFormat("0.0").format(zcjs))
			  .set("downweight", new DecimalFormat("0.0").format(dcjs))
			  .set("jinghu", jhrs)
			  .set("totalloseweight",new DecimalFormat("0.00").format(dcjs-zcjs))
			  .set("gonggurenshu",ggrs);
		if(ddrs==0){
			  record.set("proportionforloseweight","0")
			  .set("proportionforjinghu","0");
			
		}else{
			float  dcbl = (float)dcrs/(ddrs-ggrs);
//			float  jhbl = Float.parseFloat(jinghu.get("jinghu").toString())/Float.parseFloat(resultnogg.get("totalofpeople").toString());
			float  jhbl = (float)jhrs/ddrs;
			record.set("proportionforloseweight",new DecimalFormat("0.00").format(dcbl*100))
			  .set("proportionforjinghu",new DecimalFormat("0.00").format(jhbl*100));

//			record.set("proportionforloseweight",(float)Math.round(Float.parseFloat(resultdownweight.get("totalofdownweightpeople").toString())/Float.parseFloat(resultnogg.get("totalofpeople").toString())*10000)/100)
//			  .set("proportionforjinghu",(float)Math.round(Float.parseFloat(jinghu.get("jinghu").toString())/Float.parseFloat(resultnogg.get("totalofpeople").toString())*10000)/100);

		}
		return record;
	}

	public List<Record> getNearStaWeight(String cUserOrganIds) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organIds", cUserOrganIds);
		 List<Record> lis = find(CustomerService.sqlId_nearStaWeight, queryParam);
		return lis;
	}

	public void saveOrUpdateNurse(CustomerServiceNurse csmn, CustomerService cs, CustomerDetail cdet,int count,boolean isxgk) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
		String ymStr = ym.format(cs.getDate(CustomerService.column_startTime));
		String sql = "select weight from sb_customer_service where date_format(startTime, '%Y-%m') < ? and customerID = ? and organids = ? and dataStatus in ('1','2') ORDER BY startTime desc LIMIT 0,1";
		float firstWeight = cdet.getFloat(CustomerDetail.column_firstWeight);
		//查询本月第一次的服务记录
		//CustomerService  customerService = CustomerService.dao.findFirst(sql,ymStr,cs.getStr(CustomerService.column_customerID));
		//查询上月最后一次服务记录
		CustomerService  customerService = CustomerService.dao.findFirst(sql,ymStr,cs.getStr(CustomerService.column_customerID),cdet.getStr(CustomerDetail.column_organIds));
		if(csmn!=null){

			float weight2=cs.getFloat("weight");
			
			String dd = sdf.format(cs.getDate(CustomerService.column_startTime));
			
			csmn.set("weight"+dd, weight2);
			if(cs.getFloat("lastWeight")!=null && cs.getFloat("weight")!=null){
				float js = weight2-cs.getFloat("lastWeight");
				if(js<0f){
					csmn.set("weightqk"+dd, "green");
				}else if (js == 0f){
					csmn.set("weightqk"+dd, "#c7ad32");
				}else if (js>0f){
					csmn.set("weightqk"+dd, "red");
				}
			}
			
			/*Record lis = Db.findFirst(getSqlMy(CustomerService.sqlId_selSerByStratTime) , cs.getDate("startTime"),cs.getStr("customerID"));
			Float weight = 0f;
			if(lis!=null){
				 weight =lis.getFloat("weight");
				 csmn.set("weightqk"+dd, weight- weight2);
			}else{
				weight =  cdet.getFloat("firstWeight");
				csmn.set("weightqk"+dd,0);
			}*/
			
			
		
			if(customerService!=null){
				
				firstWeight = customerService.getFloat(CustomerService.column_weight);
				//csmn.set("gjWeight", firstWeight-(weight2));
			}
				csmn.set("gjWeight", firstWeight-(weight2));
			
			/*if( weight- weight2>0){
				csmn.set("gjWeight", csmn.getFloat("gjWeight")+ (weight-weight2));
			}*/
			csmn.set("ddCount",Integer.parseInt(csmn.getStr("ddCount"))+count);
			
			csmn.update();
		}else{
			float weight3=cs.getFloat("weight");
			csmn = new  CustomerServiceNurse();
			csmn.set("organids", cdet.get(CustomerDetail.column_organIds));
			csmn.set("customerID", cdet.get(CustomerDetail.column_customerIds));
			csmn.set("customerName", cdet.get(CustomerDetail.column_name));
			//日护理表是否新顾客
			if(isxgk){
				csmn.set("isXgk", "1");
			}else{
				csmn.set("isXgk", "0");
			}
			
			String dd = sdf.format(cs.getDate(CustomerService.column_startTime));
			csmn.set("weight"+dd, weight3);
			
			if(cs.getFloat("lastWeight")!=null && cs.getFloat("weight")!=null){
				float js = weight3-cs.getFloat("lastWeight");
				if(js<0f){
					csmn.set("weightqk"+dd, "green");
				}else if (js == 0f){
					csmn.set("weightqk"+dd, "#c7ad32");
				}else if (js>0f){
					csmn.set("weightqk"+dd, "red");
				}
			}
			/*Record lis = Db.findFirst(getSqlMy(CustomerService.sqlId_selSerByStratTime) , ymd.format(cs.getDate(CustomerService.column_startTime))  ,cs.getStr("customerID"));
			Float weight = 0f;
			if(lis!=null){
				 weight =lis.getFloat("weight");
				 csmn.set("weightqk"+dd, weight- weight3);
			}else{
				weight =  cdet.getFloat("firstWeight");
				csmn.set("weightqk"+dd,0);
			}
			*/
			//String sql = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ? and dataStatus in ('1','2') ORDER BY startTime  LIMIT 0,1";
			//查询本月第一次的服务记录
			//CustomerService  customerService = CustomerService.dao.findFirst(sql,ymStr,cs.getStr(CustomerService.column_customerID));
			if(customerService!=null){
				 firstWeight = customerService.getFloat(CustomerService.column_weight);
				
			}
			csmn.set("gjWeight", firstWeight-(weight3));
				//csmn.set("gjWeight", 0f);
			
			
			/*if( weight- weight3>0){
				csmn.set("gjWeight", (weight3));
			}*/
			
			
			csmn.set("ddCount",1);
			csmn.set("YearMon",ym.format(cs.getDate(CustomerService.column_startTime)));
			csmn.save();
		}
		
	}
	
	
	
	public void saveOrUpdateMonthNurse(CustomerServiceMonthNurse csmn, CustomerService cs, CustomerDetail cdet,int count,String userIds,int flag) {
		//-------------------------------------------------------------
		/*String sqlcus = "select * from sb_customer where dataStatus in ('1','2')";
		String sqlser = "SELECT * from sb_customer_service where customerID = ? and dataStatus in ('1','2') and  DATE_FORMAT(startTime, '%Y-%m') = ?  ORDER BY startTime DESC ";
		
		
		List<Customer> cusList = Customer.dao.find(sqlcus);
		for(int i = 0;i<cusList.size();i++){
			for(int j = 2015;j<=2018;j++){
				for(int m = 1 ;m<=12;m++){
					String monthstr = m+"";
					if(m<10){
						
						monthstr = "0"+m;
					}
					String cusIdsStr = cusList.get(i).getStr(Customer.column_ids);
					String sql = "select * from sb_customer_service_month_nurse where customerIds = ? and `year` = ?";
					CustomerServiceMonthNurse customerServiceMonthNurse1 = CustomerServiceMonthNurse.dao.findFirst(sql,cusIdsStr,j);
					
						String xixi = j+"-"+monthstr;
						List<CustomerService> servicelist = CustomerService.dao.find(sqlser,cusIdsStr,xixi);
						int ddcount = servicelist.size();
						CustomerService customerServicesList = CustomerService.dao.findFirst(sqlser,cusIdsStr,xixi);
						if(customerServicesList!=null){
							if(customerServiceMonthNurse1==null){
								CustomerServiceMonthNurse customerServiceMonthNurse = new CustomerServiceMonthNurse();
								customerServiceMonthNurse.set(CustomerServiceMonthNurse.column_organids, cusList.get(i).getStr(Customer.column_organIds))
								.set(CustomerServiceMonthNurse.column_customerID, cusIdsStr)
								.set(CustomerServiceMonthNurse.column_customerName, cusList.get(i).getStr(Customer.column_name))
								.set(CustomerServiceMonthNurse.column_year, j+"")
								.set("lastweight"+monthstr, customerServicesList.getFloat(CustomerService.column_weight))
								.set("ddcount"+monthstr, ddcount+"")
								.set(CustomerServiceMonthNurse.column_dataStatus, "1");
								customerServiceMonthNurse.save();
								
							}else{
								customerServiceMonthNurse1.set("lastweight"+monthstr, customerServicesList.getFloat(CustomerService.column_weight))
								.set("ddcount"+monthstr, ddcount+"");
								customerServiceMonthNurse1.update();
							}
						
						
					}
					
				}
			}
		
		}
		
		*/
		
		//-----------------------------------------------------------
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		SimpleDateFormat month = new SimpleDateFormat("MM");
		SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
		String customerIds = cdet.getStr(CustomerDetail.column_customerIds);
		String ymStr = ym.format(cs.getDate(CustomerService.column_startTime));
		String yearStr = year.format(cs.getDate(CustomerService.column_startTime));//年
		if(csmn!=null){
			float weight2=cs.getFloat("weight");
			String dd = month.format(cs.getDate(CustomerService.column_startTime));
			//flag是1为正常录入，2为补录，3为修改,0为删除
			if(flag == 1){
				csmn.set("lastweight"+dd, weight2)
				
				.set(CustomerServiceMonthNurse.column_updateDate, new Date())
				.set(CustomerServiceMonthNurse.column_updateId, userIds);
				if(csmn.getStr("ddCount"+dd)!=null&&!csmn.getStr("ddCount"+dd).equals("")){
					csmn.set("ddcount"+dd,Integer.parseInt(csmn.getStr("ddCount"+dd))+count);
				}else{
					csmn.set("ddcount"+dd,1);
				}
			}else if(flag == 2 || flag == 3 || flag == 0){
				//补录或修改
				String servicesql = getSqlMy(CustomerService.sqlId_selSerByStratTimeDESC);
				CustomerService lastService = CustomerService.dao.findFirst(servicesql,ymStr,customerIds);//本月最后一次服务记录
				if(lastService!=null){
					String lastTime = month.format(lastService.getDate(CustomerService.column_startTime));
					csmn.set("lastweight"+lastTime, lastService.getFloat(CustomerService.column_weight))
					.set(CustomerServiceMonthNurse.column_updateDate, new Date())
					.set(CustomerServiceMonthNurse.column_updateId, userIds);
					if(flag == 2){
						if(csmn.getStr("ddCount"+dd)!=null&&!csmn.getStr("ddCount"+dd).equals("")){
							csmn.set("ddcount"+dd,Integer.parseInt(csmn.getStr("ddCount"+dd))+count);
						}else{
							csmn.set("ddcount"+dd,1);
						}
						
					}
					if(flag == 0){
						if(csmn.getStr("ddCount"+dd)!=null&&!csmn.getStr("ddCount"+dd).equals("")){
							csmn.set("ddcount"+dd,Integer.parseInt(csmn.getStr("ddCount"+dd))-count);
						}else{
							csmn.set("ddcount"+dd,0);
						}
					
					}
					
				}else{
					
					csmn.set("lastweight"+dd, weight2)
					
					.set(CustomerServiceMonthNurse.column_updateDate, new Date())
					.set(CustomerServiceMonthNurse.column_updateId, userIds);
					if(csmn.getStr("ddCount"+dd)!=null&&!csmn.getStr("ddCount"+dd).equals("")){
						csmn.set("ddcount"+dd,Integer.parseInt(csmn.getStr("ddCount"+dd))+count);
					}else{
						csmn.set("ddcount"+dd,1);
					}
					
				}
			}
			
			csmn.update();
		}else{
			String dd = month.format(cs.getDate(CustomerService.column_startTime));
			float weight3=cs.getFloat("weight");
			csmn = new  CustomerServiceMonthNurse();
			csmn.set("organIds", cdet.get(CustomerDetail.column_organIds))
			.set("customerIds", cdet.get(CustomerDetail.column_customerIds))
			.set("customerName", cdet.get(CustomerDetail.column_name))
			.set("lastweight"+dd, weight3)
			.set(CustomerServiceMonthNurse.column_createDate, new Date())
			.set(CustomerServiceMonthNurse.column_createId, userIds)
			.set(CustomerServiceMonthNurse.column_dataStatus,"1")
			.set("ddcount"+dd,1)
			.set("year",yearStr);
			csmn.save();
		}
		
	}

}
